import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    //所有的数据列表
    list: [],
    //文本框内容
    inputValue: "",
    //下一个id
    nextId: 5,
    viewKey: "all"
  },
  mutations: {
    initList(state, list) {
      state.list = list;
    },
    //为store中的inputVlaue赋值
    setInputValue(state, val) {
      state.inputValue = val;
    },
    //添加列表
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      };
      state.list.push(obj);
      state.nextId++;
      state.inputValue = "";
    },
    //根据id删
    removeItem(state, id) {
      //id找对应的索引
      const i = state.list.findIndex(x => x.id === id);
      //根据索引删除元素
      if (i !== -1) {
        state.list.splice(i, 1);
      }
    },
    //修改列表项的选中
    changeStatus(state, param) {
      //找索引
      const i = state.list.findIndex(x => x.id === param.id);
      //找对象
      if (i !== -1) {
        state.list[i].done = param.status;
      }
    },
    //清除已完成
    clearDone(state) {
      state.list = state.list.filter(x => x.done === false);
    },
    //修改视图的关健字
    changeViewKey(state, key) {
      state.viewKey = key;
    }
  },
  actions: {
    getList(context) {
      axios.get("/list.json").then(({ data }) => {
        console.log(data);
        context.commit("initList", data);
      });
    }
  },
  getters: {
    //统计为完成的数据
    unDoneLength(state) {
      return state.list.filter(x => x.done === false).length;
    },
    //选择性的返回对应数据
    infoList(state) {
      if (state.viewKey === "all") {
        return state.list;
      }
      if (state.viewKey === "undone") {
        return state.list.filter(x => !x.done);
      }
      if (state.viewKey === "done") {
        return state.list.filter(x => x.done);
      }
      return state.list;
    }
  }
});
